/**
 * @description 系统初始化工具
 * @author 张一依有把越女剑
 * @date 2025-04-16
 */

import { logger, errorHandler } from './errorHandler.js'
import { dataBackupManager } from './dataBackup.js'
import { performanceMonitor } from './performance.js'
import { cacheManager } from './performance.js'

// 系统初始化管理器
export class SystemInitializer {
	constructor() {
		this.initSteps = []
		this.isInitialized = false
	}
	
	// 添加初始化步骤
	addInitStep(name, initFunction) {
		this.initSteps.push({
			name,
			init: initFunction
		})
	}
	
	// 执行系统初始化
	async initialize() {
		if (this.isInitialized) {
			logger.info('System already initialized')
			return { success: true, message: 'Already initialized' }
		}
		
		logger.info('Starting system initialization...')
		
		try {
			// 执行所有初始化步骤
			for (const step of this.initSteps) {
				logger.info(`Initializing ${step.name}...`)
				await step.init()
				logger.info(`${step.name} initialized successfully`)
			}
			
			this.isInitialized = true
			logger.info('System initialization completed successfully')
			
			return { success: true, message: 'System initialized successfully' }
		} catch (error) {
			logger.error('System initialization failed', error)
			errorHandler.reportError(error, 'System Initialization')
			return { success: false, error: error.message }
		}
	}
	
	// 检查系统状态
	checkSystemHealth() {
		const healthCheck = {
			timestamp: Date.now(),
			status: 'healthy',
			checks: {}
		}
		
		try {
			// 检查存储
			healthCheck.checks.storage = this.checkStorage()
			
			// 检查备份系统
			healthCheck.checks.backup = this.checkBackupSystem()
			
			// 检查性能
			healthCheck.checks.performance = this.checkPerformance()
			
			// 检查错误处理
			healthCheck.checks.errorHandling = this.checkErrorHandling()
			
			// 判断整体状态
			const failedChecks = Object.values(healthCheck.checks).filter(check => !check.status)
			if (failedChecks.length > 0) {
				healthCheck.status = 'warning'
			}
			
			logger.info('System health check completed', healthCheck)
			return healthCheck
		} catch (error) {
			logger.error('System health check failed', error)
			healthCheck.status = 'error'
			healthCheck.error = error.message
			return healthCheck
		}
	}
	
	// 检查存储系统
	checkStorage() {
		try {
			const testKey = 'system_health_test'
			const testValue = { timestamp: Date.now() }
			
			uni.setStorageSync(testKey, testValue)
			const retrieved = uni.getStorageSync(testKey)
			uni.removeStorageSync(testKey)
			
			const storageInfo = uni.getStorageInfoSync()
			
			return {
				status: true,
				message: 'Storage system working',
				details: {
					currentSize: storageInfo.currentSize,
					limitSize: storageInfo.limitSize,
					usage: Math.round((storageInfo.currentSize / storageInfo.limitSize) * 100)
				}
			}
		} catch (error) {
			return {
				status: false,
				message: 'Storage system error',
				error: error.message
			}
		}
	}
	
	// 检查备份系统
	checkBackupSystem() {
		try {
			const backupList = dataBackupManager.getBackupList()
			const storageInfo = dataBackupManager.getStorageInfo()
			
			return {
				status: true,
				message: 'Backup system working',
				details: {
					backupCount: backupList.length,
					lastBackup: backupList.length > 0 ? backupList[0].date : 'Never',
					storageUsage: storageInfo
				}
			}
		} catch (error) {
			return {
				status: false,
				message: 'Backup system error',
				error: error.message
			}
		}
	}
	
	// 检查性能
	checkPerformance() {
		try {
			const performanceReport = performanceMonitor.getReport()
			
			return {
				status: true,
				message: 'Performance monitoring working',
				details: performanceReport
			}
		} catch (error) {
			return {
				status: false,
				message: 'Performance monitoring error',
				error: error.message
			}
		}
	}
	
	// 检查错误处理
	checkErrorHandling() {
		try {
			// 测试日志系统
			logger.debug('Health check test log')
			
			return {
				status: true,
				message: 'Error handling system working'
			}
		} catch (error) {
			return {
				status: false,
				message: 'Error handling system error',
				error: error.message
			}
		}
	}
	
	// 清理系统
	async cleanup() {
		try {
			logger.info('Starting system cleanup...')
			
			// 清理缓存
			cacheManager.cleanup()
			
			// 清理过期日志
			this.cleanupLogs()
			
			// 清理临时数据
			this.cleanupTempData()
			
			logger.info('System cleanup completed')
			return { success: true }
		} catch (error) {
			logger.error('System cleanup failed', error)
			return { success: false, error: error.message }
		}
	}
	
	// 清理日志
	cleanupLogs() {
		try {
			const logs = uni.getStorageSync('app_logs') || []
			const maxLogs = 500
			
			if (logs.length > maxLogs) {
				const cleanedLogs = logs.slice(-maxLogs)
				uni.setStorageSync('app_logs', cleanedLogs)
				logger.info(`Cleaned up logs, kept ${cleanedLogs.length} entries`)
			}
		} catch (error) {
			logger.warn('Failed to cleanup logs', error)
		}
	}
	
	// 清理临时数据
	cleanupTempData() {
		try {
			const tempKeys = ['temp_', 'cache_', 'tmp_']
			const storageInfo = uni.getStorageInfoSync()
			
			storageInfo.keys.forEach(key => {
				if (tempKeys.some(prefix => key.startsWith(prefix))) {
					try {
						uni.removeStorageSync(key)
					} catch (error) {
						logger.warn(`Failed to remove temp key: ${key}`, error)
					}
				}
			})
		} catch (error) {
			logger.warn('Failed to cleanup temp data', error)
		}
	}
}

// 创建全局系统初始化器实例
export const systemInitializer = new SystemInitializer()

// 添加默认初始化步骤
systemInitializer.addInitStep('Error Handler', async () => {
	// 错误处理系统已在导入时自动初始化
	logger.info('Error handling system ready')
})

systemInitializer.addInitStep('Performance Monitor', async () => {
	// 性能监控系统已在导入时自动初始化
	logger.info('Performance monitoring system ready')
})

systemInitializer.addInitStep('Cache Manager', async () => {
	// 清理过期缓存
	cacheManager.cleanup()
	logger.info('Cache manager ready')
})

systemInitializer.addInitStep('Backup System', async () => {
	// 检查备份系统状态
	const backupList = dataBackupManager.getBackupList()
	logger.info(`Backup system ready, ${backupList.length} backups available`)
})

// 导出便捷方法
export async function initializeSystem() {
	return await systemInitializer.initialize()
}

export function checkSystemHealth() {
	return systemInitializer.checkSystemHealth()
}

export async function cleanupSystem() {
	return await systemInitializer.cleanup()
}

// 自动初始化（在应用启动时调用）
export async function autoInit() {
	try {
		const result = await initializeSystem()
		if (result.success) {
			logger.info('System auto-initialization completed')
		} else {
			logger.error('System auto-initialization failed', result.error)
		}
		return result
	} catch (error) {
		logger.error('System auto-initialization error', error)
		return { success: false, error: error.message }
	}
}
